<template>
    <div class="Department-management">
        <!-- 搜索栏 -->
        <div class="search-bar">
            <el-input v-model="searchQuery" placeholder="请输入科室名称" clearable @clear="handleSearch"
                @keyup.enter="handleSearch">
                <template #append>
                    <el-button :icon="Search" @click="handleSearch" />
                </template>
            </el-input>
            <el-button type="primary" :icon="Plus" @click="handleAddDepartment">新增科室</el-button>
        </div>

        <!-- 科室列表 -->
        <el-table :data="filteredDepartments" stripe style="width: 100%" @row-click="handleRowClick">
            <el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label"
                :sortable="column.sortable" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="text" :icon="Edit" @click.stop="handleEdit(scope.row)">编辑</el-button>
                    <el-button type="text" :icon="Delete" @click.stop="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalDepartments"
                layout="total, sizes, prev, pager, next, jumper" @current-change="handlePageChange" />
        </div>

        <!-- 科室详情抽屉 -->
        <el-drawer v-model="drawerVisible" title="科室详情" size="40%">
            <div v-if="selectedDepartment">
                <h3>{{ selectedDepartment.name }} 科室的详细信息</h3>
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="名称">{{ selectedDepartment.name }}</el-descriptions-item>
                    <el-descriptions-item label="名称">{{ selectedDepartment.type }}</el-descriptions-item>
                </el-descriptions>
            </div>
        </el-drawer>
        <!-- 新增/编辑科室对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑科室' : '新增科室'">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="科室">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="部门">
                    <el-radio-group v-model="form.type">
                        <el-radio label="门诊部" value="门诊部" :key="form.type" />
                        <el-radio label="住院部" value="住院部" :key="form.type" />
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="submit" @click="handleSubmit">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { PostDepartment, DeleteDepartment, PutDepartment, GetDepartments } from '@/api/DepartmentService'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const columns = [
    { prop: 'name', label: '科室', sortable: true },
    { prop: 'type', label: '部门', sortable: true },
]
// 表单验证规则
const rules = ref({
    name: [
        { required: true, message: t('cannotBlank', { field: t('name') }), trigger: 'blur' },
        { min: 2, max: 5, message: '科室姓名长度应为 2 到 5 个字符', trigger: 'blur' }
    ]
})
//获取科室列表
const Departments = ref<any>([])

onMounted(async () => {
    const response = await GetDepartments()
    Departments.value = response.data
})
// 搜索功能
const searchQuery = ref('')
const filteredDepartments = computed(() => {
    return Departments.value.filter(Department =>
        Department.name.includes(searchQuery.value))
})
// 分页功能
const currentPage = ref(1)
const pageSize = ref(10)
const totalDepartments = computed(() => filteredDepartments.value.length)

const drawerVisible = ref(false)
const selectedDepartment = ref<any>(null)
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = ref<any>({
    id: 0,
    name: "",
    type: ""
})
// 方法
const handleSearch = () => {
    currentPage.value = 1
}

const handleRowClick = (Department) => {
    selectedDepartment.value = Department
    drawerVisible.value = true
}

//编辑
const handleEdit = (Department) => {
    // form.value = { ...Department }
    // const deleteProp = ['appointments', 'department', 'medicalRecords']
    // deleteProp.forEach(property => {
    //     delete form.value[property]
    // })
    form.value = {
        id: Department.id,
        name: Department.name,
        type: Department.type
    }
    isEdit.value = true
    dialogVisible.value = true
}
//新增
const handleAddDepartment = () => {
    form.value = {
        id: 0,
        name: "",
        type: ""
    }
    isEdit.value = false
    dialogVisible.value = true
}
//删除
const handleDelete = (Department) => {
    Departments.value = Departments.value.filter(p => p.id !== Department.id)
    DeleteDepartment(Department.id)
}
//提交
const handleSubmit = () => {
    const request = {
        type: form.value.type,
        name: form.value.name,
        id: form.value.id
    }
    if (request.type === '' || request.name === '') { alert("请填写完整数据"); return }
    formRef.value.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                const index = Departments.value.findIndex(p => p.id === request.id)
                Departments.value[index] = { ...request }
                // PatchDepartmentApi(form.value.id, form.value)
                PutDepartment(request.id, request)
                console.log('编辑科室:', form.value)
            } else {
                Departments.value.push({ ...request, id: Departments.value.length + 1 })
                PostDepartment(request)
                alert("新增成功")
                console.log('新增科室:', request)
            }
            dialogVisible.value = false
        }
        else {
            console.log("表单验证失败");
        }
    })
}


const formRef = ref<any>(null)

const handlePageChange = (page) => {
    currentPage.value = page
}


</script>

<style scoped>
.Department-management {
    padding: 20px;
}

.search-bar {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}
</style>